package com.java2007.hotel.controller;

import com.alibaba.druid.util.StringUtils;
import com.java2007.hotel.constant.Constant;
import com.java2007.hotel.factory.BeanFactory;
import com.java2007.hotel.pojo.Admin;
import com.java2007.hotel.pojo.Food;
import com.java2007.hotel.pojo.FoodType;
import com.java2007.hotel.service.FoodService;
import com.java2007.hotel.service.FoodTypeService;
import com.java2007.hotel.service.impl.FoodServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 处理菜品有关的请求
 *
 * @author csl
 * @version V1.0
 * @date 2021/01/23
 **/
@WebServlet("/hotel/foodServlet")
@MultipartConfig(maxFileSize = 1024 * 1024 * 100, maxRequestSize = 1024 * 1024 * 1000)
public class FoodServlet extends BaseServlet {
    private FoodService foodService = (FoodService) BeanFactory.getBean(Constant.FOOD_SERVICE_IMPL);
    private FoodTypeService foodTypeService = (FoodTypeService) BeanFactory.getBean(Constant.FOOD_TYPE_SERVICE_IMPL);

    /**
     * 查询所有菜品
     *
     * @return
     */
    public String selectAll(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        List<Food> foods = null;
        try {
            foods = foodService.selectAll();
        } catch (SQLException e) {
            e.printStackTrace();
            return "upIndex";
        }
        session.setAttribute("foods", foods);
        return "redirect:" + req.getContextPath() + "/hotel/backend/detail/food/foodList.jsp";
    }

    /**
     * 添加菜品前回显菜系
     *
     * @param req
     * @param resp
     * @return
     */
    public String beforeSave(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        try {
            List<FoodType> foodTypes = foodTypeService.selectAllFoodType();
            session.setAttribute("beforeSaveFoodTypes", foodTypes);
        } catch (SQLException e) {
            e.printStackTrace();
            return "toIndex";
        }
        return "redirect:" + req.getContextPath() + "/hotel/backend/detail/food/foodSave.jsp";
    }

    /**
     * 添加一个菜品
     *
     * @param req
     * @param resp
     * @return
     */
    public String addFood(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String foodName = req.getParameter("foodName");
        String price = req.getParameter("price");
        String mprice = req.getParameter("mprice");
        String introduce = req.getParameter("introduce");
        String cid = req.getParameter("cid");
        double bDouble = Double.parseDouble(price) * 100;
        double bDouble1 = Double.parseDouble(mprice) * 100;
        Long aDouble = (long) bDouble;
        Long aDouble1 = (long) bDouble1;
        Part part = null;
        try {
            part = req.getPart("imageUrl");
        } catch (Exception e) {
            e.printStackTrace();
            return "toIndex";
        }
        String filename = null;
        //原始文件名\
        if (null != part) {
            filename = part.getSubmittedFileName();
        }

        String newFileName = this.setImg(filename, part, req);
        Admin admin = (Admin) req.getSession().getAttribute("admin");
        Food food = new Food(null, foodName, Integer.valueOf(cid), aDouble, aDouble1, newFileName, introduce, null, new Date(), admin.getId(), null);
        System.out.println(food);
        int i = foodService.addFood(food);
        return "redirect:" + req.getContextPath() + "/hotel/foodServlet?method=selectAll";
    }

    /**
     * 保存图片
     *
     * @param filename
     * @param part
     * @param req
     * @return 返回图片名
     * @throws IOException
     */
    private String setImg(String filename, Part part, HttpServletRequest req) throws IOException {
        //保证文件不重名，重构文件名，且需要保证文件名唯一
        String uuidName = UUID.randomUUID().toString().replaceAll("-", "");
        //得到原始文件名的后缀
        int lastPointIndex = filename.lastIndexOf(".");
        String extName = filename.substring(lastPointIndex);
        String newFileName = uuidName.concat(extName);
        if (!StringUtils.isEmpty(filename)) {
            //获取应用在tomcat的真实路径
            String realPath = req.getServletContext().getRealPath("/images/" + newFileName);
            System.out.println("-> " + realPath);

            File file = new File(realPath);
            if (!file.getParentFile().exists()) {
                file.mkdirs();
            }
            part.write(realPath);
            System.out.println("文件上传完成.........");
        } else {
            System.out.println("文件不能为空.........");
        }
        return newFileName;
    }

    /**
     * 删除一个菜品
     *
     * @param req
     * @param resp
     * @return
     */
    public String delete(HttpServletRequest req, HttpServletResponse resp) {
        String pageId = req.getParameter("pageId");
        try {
            int i = foodService.deleteFoodById(Integer.parseInt(pageId));
            if (i == 2){
                return "back:" + "由于订单详情中含有该菜品，禁止删除！%"+"hotel/foodServlet?method=selectAll";
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "toIndex";
        }


        return "redirect:" + req.getContextPath() + "/hotel/foodServlet?method=selectAll";
    }

    /**
     * 模糊查询菜品
     * @param req
     * @param resp
     * @return
     */
    public String search(HttpServletRequest req, HttpServletResponse resp) {
        String keyword = req.getParameter("keyword").trim();
        HttpSession session = req.getSession();
        List<Food> foods = null;
        if (!com.mysql.cj.util.StringUtils.isNullOrEmpty(keyword)){
            try {
                foods = foodService.selectFoodByName(keyword);
            } catch (SQLException e) {
                e.printStackTrace();
                return "toIndex";
            }
            session.setAttribute("foods", foods);
            return "redirect:" + req.getContextPath() + "/hotel/backend/detail/food/foodList.jsp";
        }else {
            return "redirect:" + req.getContextPath() + "/hotel/foodServlet?method=selectAll";
        }

    }

    /**
     * 更新菜品前回显数据
     * @param req
     * @param resp
     * @return
     */
    public String beforeUpdate(HttpServletRequest req, HttpServletResponse resp){
        String pageId = req.getParameter("pageId");
        HttpSession session = req.getSession();
        Food food = null;
        try {
            food = foodService.selectFoodById(Integer.parseInt(pageId));
        } catch (SQLException e) {
            e.printStackTrace();
            return "toIndex";
        }
        session.setAttribute("beforeUpdateFood",food);

        List<FoodType> foodTypes = null;
        try {
            foodTypes = foodTypeService.selectAllFoodType();
        } catch (SQLException e) {
            e.printStackTrace();
            return "toIndex";
        }
        session.setAttribute("beforeUpdateCuisines",foodTypes);


        return "redirect:" + req.getContextPath() + "/hotel/backend/detail/food/foodUpdate.jsp";
    }

    /**
     * 更新菜品数据
     * @param req
     * @param resp
     * @return
     */
    public String  upDateFood(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String foodName = req.getParameter("foodName");
        String price = req.getParameter("price");
        String mprice = req.getParameter("mprice");
        String introduce = req.getParameter("introduce");
        String cid = req.getParameter("cid");

        String id = req.getParameter("id");


        double bDouble = Double.parseDouble(price) * 100;
        double bDouble1 = Double.parseDouble(mprice) * 100;
        Long aDouble = (long) bDouble;
        Long aDouble1 = (long) bDouble1;
        Part part = null;
        try {
            part = req.getPart("imageUrl");
        } catch (Exception e) {
            e.printStackTrace();
            return "toIndex";
        }
        //原始文件名\
        String filename = part.getSubmittedFileName();


        String newFileName = null;
        Food originalFood = (Food) req.getSession().getAttribute("beforeUpdateFood");;
        if (!com.mysql.cj.util.StringUtils.isNullOrEmpty(filename)){
            //删除图片文件
            String originalPath = req.getServletContext().getRealPath("/detail/style/images/" + originalFood.getPicture());
            System.out.println("-> " + originalPath);
            File file = new File(originalPath);
            file.delete();
            newFileName = this.setImg(filename, part, req);
        }else {
            newFileName = originalFood.getPicture();
        }

        Admin admin = (Admin) req.getSession().getAttribute("admin");
        Food food = new Food(Integer.parseInt(id), foodName, Integer.valueOf(cid), aDouble, aDouble1, newFileName, introduce, null, null, admin.getId(), null);
        System.out.println(food);
        int i = foodService.updateFood(food);
        return "redirect:" + req.getContextPath() + "/hotel/foodServlet?method=selectAll";
    }

    /**
     * 查询菜系是否存在
     * @param req
     * @param resp
     * @return
     */
    public String isbName(HttpServletRequest req, HttpServletResponse resp){
        String keyword = req.getParameter("bName").trim();
        if (!com.mysql.cj.util.StringUtils.isNullOrEmpty(keyword)){

            try {
                Food food = foodService.selectFoodByNameOne(keyword);
                System.out.println(food == null);
                if (food != null){
                    return "backText:"+"err";
                }else {
                    return "backText:"+"success";
                }
            } catch (SQLException e) {
                e.printStackTrace();
                return "toIndex";
            }

        }else {
            return "backText:"+"wu";
        }

    }

}
